package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.properties.TcConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.entity.BtyShop;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyShopMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyShopParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyShopResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyShopService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangge
 * @since 2020-09-04
 */
@Service
public class BtyShopServiceImpl extends ServiceImpl<BtyShopMapper, BtyShop> implements BtyShopService {
    private Logger logger = LoggerFactory.getLogger(BtyShopServiceImpl.class);
    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private TcConfig tcConfig;
    @Override
    public void add(BtyShopParam param) {
        BtyShop entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyShopParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyShopParam param) {
        BtyShop oldEntity = getOldEntity(param);
        BtyShop newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyShopResult findBySpec(BtyShopParam param) {
        return null;
    }

    @Override
    public List<BtyShopResult> findListBySpec(BtyShopParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyShopParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData initShopData() {
        String url = "http://btyjt.c3.fxscm.net/cldpoint/getShop.do?ent=ENT7617&username="+tcConfig.getUsername()+"&password="+tcConfig.getPassword();
        String content = restTemplate.getForObject(url, String.class);
        JSONObject resultObject = JSON.parseObject(content);
        JSONArray jsonArray = resultObject.getJSONArray("data");

        JSONObject jsonObject;
        List<BtyShopParam> list = Lists.newLinkedList();
        logger.info("门店数据入库开始：{}条数据", jsonArray.size());
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.size(); i++) {
                BtyShopParam btyShop = new BtyShopParam();
                //把所有 ItemSmallClassName 为 酱料 的添加到list中
                jsonObject = jsonArray.getJSONObject(i);

                btyShop.setShopId(jsonObject.getOrDefault("shopid", "").toString());
                btyShop.setShopCode(jsonObject.getOrDefault("shopCode", "").toString());
                if(jsonObject.getOrDefault("JoinFlag", "").toString().equals("")){
                    btyShop.setJoinFlag(null);
                }else {
                    btyShop.setJoinFlag(Integer.valueOf(jsonObject.getOrDefault("JoinFlag", "").toString()));
                }

                Date modifyDate = DateUtil.getTimeToDate(jsonObject.getOrDefault("modifyDate", "").toString());
                btyShop.setModifyDate(modifyDate);
                btyShop.setPhone(jsonObject.getOrDefault("Phone", "").toString());
                btyShop.setShopName(jsonObject.getOrDefault("shopName", "").toString());

                if(jsonObject.getOrDefault("enableFlag", "").toString().equals("")){
                    btyShop.setEnableFlag(null);
                }else {
                    btyShop.setEnableFlag(Integer.valueOf(jsonObject.getOrDefault("enableFlag", "").toString()));
                }
                btyShop.setParentId(jsonObject.getOrDefault("parentid", "").toString());
                btyShop.setAddr(jsonObject.getOrDefault("ADDR", "").toString());

                list.add(btyShop);
            }
        }

        //如果有数据则清空店铺表再插入，以免之前的数据也丢失了
        if(list.size()>0){
            deleteAllShops();
        }

        //插入数据
        for (BtyShopParam btyShop : list) {
            add(btyShop);
        }

        logger.info("门店数据入库结束：{}条数据", list.size());

        return ResponseData.success();
    }

    @Override
    public List<BtyShopResult> selectAllShop(BtyShopParam btyShopParam) {
        List<BtyShopResult> btyShopResultList = this.baseMapper.selectAllShop(btyShopParam);
        return btyShopResultList;
    }

    /**
     * 删除所有的店铺数据
     */
    private void deleteAllShops() {
        this.baseMapper.deleteAllShops();
    }


    private Serializable getKey(BtyShopParam param) {
        return param.getShopId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyShop getOldEntity(BtyShopParam param) {
        return this.getById(getKey(param));
    }

    private BtyShop getEntity(BtyShopParam param) {
        BtyShop entity = new BtyShop();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
